package com.test.deencredit.activity_deencredit;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.test.deencredit.analytics_deencredit.event_deencredit.IAnalyticsEvent_deencredit;
import com.test.deencredit.analytics_deencredit.util_deencredit.AnalyticsUtil_deencredit;
import com.test.deencredit.R;
import com.test.deencredit.activity_deencredit.ln_deencredit.MainActivity_deencredit;
import com.test.deencredit.base_deencredit.BaseActivity_deencredit;
import com.test.deencredit.bean_deencredit.config_deencredit.AppShowCustomize_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.LoginInfo_deencredit;
import com.test.deencredit.bean_deencredit.userinfo_deencredit.OthersInfo_deencredit;
import com.test.deencredit.config_deencredit.CountryConfig_deencredit;
import com.test.deencredit.dialog_deencredit.CustomerServiceDialog_deencredit;
import com.test.deencredit.util_deencredit.UserInfoUtil_deencredit;
import com.test.deencredit.util_deencredit.http_deencredit.HttpUtil_deencredit;
import com.test.deencredit.view_deencredit.NumberTextView_S_deencredit;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity_deencredit extends BaseActivity_deencredit {

    private EditText mobileEt_deencredit, vercodeEt_deencredit;
    private Button getcodeBtn_deencredit;
    private ImageButton agreementIb_deencredit;

    private boolean agreementFlag_deencredit = true;

    private final View.OnClickListener sendCodeCl_deencredit = v -> {

        String mobile = mobileEt_deencredit.getText().toString().trim();

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtil_deencredit.getInstance_deencredit().requestOtpCode_deencredit(this,mobile,this::onSendCodeResponse_deencredit);
    };

    private final View.OnClickListener loginCl_deencredit = v -> {

        String mobile = mobileEt_deencredit.getText().toString().trim();
        String vercode = vercodeEt_deencredit.getText().toString().trim();

        HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"CONFIRM_CLICK",mobile);

        if (TextUtils.isEmpty(mobile)){
            Toast.makeText(this,getString(R.string.tips_enter_mobile_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(vercode)){
            Toast.makeText(this,getString(R.string.tips_enter_vercode_deencredit),Toast.LENGTH_SHORT).show();
            return;
        }

        //测试账号自动登录
        if (AppShowCustomize_deencredit.getInstance_deencredit().isTestAccount_deencredit(mobile)){
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("token", AppShowCustomize_deencredit.getInstance_deencredit().getTestToken_deencredit(mobile));
                jsonObject.put("userId", mobile);
                jsonObject.put("type", UserInfoUtil_deencredit.LOGIN_TYPE_OLD_deencredit);
                jsonObject.put("isAdSource","NO");
                LoginInfo_deencredit.parse_deencredit(jsonObject);
                onLoginSuccessResponse_deencredit();
            }catch (JSONException e){
                e.printStackTrace();
            }
            return;
        }

        HttpUtil_deencredit.getInstance_deencredit().userLg_deencredit(this,mobile,vercode,this::onLoginSuccessResponse_deencredit);

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_deencredit);

        page_deencredit = "LOGIN";

        init_deencredit();
    }

    private void init_deencredit(){

        findViewById(R.id.alg_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog_deencredit(this).show());

        NumberTextView_S_deencredit loanamountNtv = findViewById(R.id.alg_ntv_loanamount);
        NumberTextView_S_deencredit interestrateNtv = findViewById(R.id.alg_ntv_interestrate);
        TextView interestratecycleTv = findViewById(R.id.alg_tv_interestratecycle);
        SeekBar amountSeekbar = findViewById(R.id.alg_seekbar_amount);
        TextView minamountTv = findViewById(R.id.alg_tv_minamount);
        TextView maxamountTv = findViewById(R.id.alg_tv_maxamount);

        TextView areacodeTv = findViewById(R.id.alg_tv_areacode);
        TextView mobiletitleTv = findViewById(R.id.alg_tv_mobiletitle);
        mobileEt_deencredit = findViewById(R.id.alg_et_mobile);
        vercodeEt_deencredit = findViewById(R.id.alg_et_vercode);
        getcodeBtn_deencredit = findViewById(R.id.alg_btn_getcode);
        Button loginBtn = findViewById(R.id.alg_btn_login);
        agreementIb_deencredit = findViewById(R.id.alg_ib_agreement);
        TextView agreementTv = findViewById(R.id.alg_tv_agreement);

        //肯尼亚手机号标题
        if (CountryConfig_deencredit.getInstance_deencredit().isKenya_deencredit()){
            mobiletitleTv.setText(getString(R.string.login_mobile_title_kenya_deencredit));
        }

        //初始化登录流程
        String areaCode = CountryConfig_deencredit.getInstance_deencredit().getAreaCode_deencredit();
        areacodeTv.setText(areaCode);
        UserInfoUtil_deencredit.getInstance_deencredit().setAreaCode_deencredit(areaCode);

        getcodeBtn_deencredit.setOnClickListener(sendCodeCl_deencredit);
        loginBtn.setOnClickListener(loginCl_deencredit);

        //初始化协议
        agreementIb_deencredit.setOnClickListener(v -> setAgreementFlag_deencredit(!agreementFlag_deencredit));
        agreementTv.setOnClickListener(v -> {
            HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"STATEMENT_CLICK","");
            String agreementUrl = AppShowCustomize_deencredit.getInstance_deencredit().getAgreementUrl_deencredit();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //初始化额度显示
        interestrateNtv.setText_deencredit(AppShowCustomize_deencredit.getInstance_deencredit().getLoginInterestRate_deencredit());
        interestratecycleTv.setText(AppShowCustomize_deencredit.getInstance_deencredit().getLoginInterestRateCycle_deencredit());

        String minAmountStr = AppShowCustomize_deencredit.getInstance_deencredit().getLoginMinAmount_deencredit();
        String maxAmountStr = AppShowCustomize_deencredit.getInstance_deencredit().getLoginMaxAmount_deencredit();
        String amountGranularityStr = AppShowCustomize_deencredit.getInstance_deencredit().getLoginAmountGranularity_deencredit();

        minamountTv.setText(minAmountStr);
        maxamountTv.append(" "+maxAmountStr);

        loanamountNtv.setText_deencredit(minAmountStr);

        try {
            int minAmount = Integer.parseInt(minAmountStr);
            int maxAmount = Integer.parseInt(maxAmountStr);
            int amountGranularity = Integer.parseInt(amountGranularityStr);

            amountSeekbar.setMin(minAmount/amountGranularity);
            amountSeekbar.setMax(maxAmount/amountGranularity);

            amountSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    loanamountNtv.setText_deencredit(String.valueOf(seekBar.getProgress()*amountGranularity));
                }
                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}
                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {}
            });
        }catch (NumberFormatException e){
            e.printStackTrace();
        }

        //验证码输入监听
        vercodeEt_deencredit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4){

                    String mobile = mobileEt_deencredit.getText().toString().trim();
                    String vercode = vercodeEt_deencredit.getText().toString().trim();

                    HttpUtil_deencredit.getInstance_deencredit().saveBuriedPoint_deencredit(page_deencredit,"OTP_DONE",vercode);

                    if (TextUtils.isEmpty(mobile)) return;

                    //测试账号自动登录
                    if (AppShowCustomize_deencredit.getInstance_deencredit().isTestAccount_deencredit(mobile)){
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("token", AppShowCustomize_deencredit.getInstance_deencredit().getTestToken_deencredit(mobile));
                            jsonObject.put("userId", mobile);
                            jsonObject.put("type", UserInfoUtil_deencredit.LOGIN_TYPE_OLD_deencredit);
                            jsonObject.put("isAdSource","NO");
                            LoginInfo_deencredit.parse_deencredit(jsonObject);
                            onLoginSuccessResponse_deencredit();
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        return;
                    }

                    HttpUtil_deencredit.getInstance_deencredit().userLg_deencredit(LoginActivity_deencredit.this,mobile,vercode,() -> onLoginSuccessResponse_deencredit());

                }
            }
        });

    }

    private void setAgreementFlag_deencredit(boolean agreementFlag_deencredit) {
        this.agreementFlag_deencredit = agreementFlag_deencredit;
        agreementIb_deencredit.setBackgroundResource(agreementFlag_deencredit ? R.drawable.icon_permission_agreement_check_true_deencredit :R.drawable.icon_permission_agreement_check_false_deencredit);
    }

    @SuppressLint("SetTextI18n")
    public void onSendCodeResponse_deencredit(){

        Toast.makeText(this,getString(R.string.tips_vercode_send_success_deencredit),Toast.LENGTH_SHORT).show();
        getcodeBtn_deencredit.setOnClickListener(null);

        //老用户直接登录
        String mobile = mobileEt_deencredit.getText().toString().trim();
        JSONObject jsonObject = OthersInfo_deencredit.getInstance_deencredit().getSendOtpCodeJson_deencredit();
        if (jsonObject!=null){
            String directLogin = jsonObject.optString("directLoginFlag");
            if (directLogin.equalsIgnoreCase("YES")) {
                HttpUtil_deencredit.getInstance_deencredit().userLoginOldUser_deencredit(this,mobile,this::onLoginSuccessResponse_deencredit);
                return;
            }
        }

        getcodeBtn_deencredit.setBackgroundResource(R.drawable.bg_purple_gray_rc24dp_deencredit);

        new Thread(() -> {

            int count = 60;

            while (count-- > 0){
                final int finalCount = count;
                runOnUiThread(() -> getcodeBtn_deencredit.setText(finalCount+"s"));
                try {
                    Thread.sleep(999);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(() -> {
                getcodeBtn_deencredit.setBackgroundResource(R.drawable.bg_purple_rc_24dp_deencredit);
                getcodeBtn_deencredit.setOnClickListener(sendCodeCl_deencredit);
                getcodeBtn_deencredit.setText(getString(R.string.get_code_deencredit));
            });

        }).start();

    }

    public void onLoginSuccessResponse_deencredit(){

        UserInfoUtil_deencredit.getInstance_deencredit().setMobile_deencredit(mobileEt_deencredit.getText().toString());
        UserInfoUtil_deencredit.getInstance_deencredit().setToken_deencredit(LoginInfo_deencredit.getInstance().getToken_deencredit());
        UserInfoUtil_deencredit.getInstance_deencredit().setUserId_deencredit(LoginInfo_deencredit.getInstance().getUserId_deencredit());
        UserInfoUtil_deencredit.getInstance_deencredit().setIsAdSource_deencredit(LoginInfo_deencredit.getInstance().getIsAdSource_deencredit());

        if (LoginInfo_deencredit.getInstance().getType_deencredit().equalsIgnoreCase(UserInfoUtil_deencredit.LOGIN_TYPE_REGISTER_deencredit))
            AnalyticsUtil_deencredit.INSTANCE.addEvent_deencredit(IAnalyticsEvent_deencredit.AT_REGISTER);

        AnalyticsUtil_deencredit.INSTANCE.saveFirebaseAndFacebookS2SInfo_deencredit();

        HttpUtil_deencredit.getInstance_deencredit().userProcess_deencredit(this,this::onUserProcessResponse_deencredit);

    }

    public void onUserProcessResponse_deencredit(){
        startActivity(new Intent(this, MainActivity_deencredit.class));
        finish();
    }

}